package hanelsoft.vn.dictionaylearn.control.activity;

import hanelsoft.vn.dictionaylearn.R;
import hanelsoft.vn.dictionaylearn.model.common.Utility;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFile;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFileList;
import hanelsoft.vn.dictionaylearn.model.db.VocabularySQLiteHelper;
import hanelsoft.vn.dictionaylearn.model.entity.InfoHistory;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabulary;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabularyContent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class ContentView extends Activity {

	static final private String CONTENT_TAG = "[Content]";
	private static final String MIMETYPE = "text/html";
    private static final String ENCODING = "UTF-8";
    private TextView contentview_Sound;
    private WebView contentview_Content = null;
    private String mCurrentWord;
    private String mSelectedDB;
    private String mContentStyle;
    private String mSourcesound;
    InfoVocabulary infoGetVocabulary;
    ArrayList<InfoVocabulary>arrayVocabulary;
    ArrayList<String> mWordHistory = null;
    private int mCurrentWordId;
    int VIEW_RADIO_ID = 12100702;
    String fullPathFilePro;
    MediaPlayer mp;
    Menu menu = null;
    SharedPreferences shareSaveHistory, sharePlaySound;
	@SuppressWarnings("unused")
	private SharedPreferences prefs;
	File f;
	private ProgressDialog pd = null;
	String content;
	VocabularySQLiteHelper mVocabularySQLiteHelper = new VocabularySQLiteHelper(this);
    @Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    //requestWindowFeature(Window.FEATURE_NO_TITLE); 
	    setContentView(R.layout.content);
	    Intent i = this.getIntent();
	    int wordId = i.getIntExtra("id", -1);
	    mCurrentWord = i.getStringExtra("word");
	    mSelectedDB = i.getStringExtra("db");
	    mContentStyle = i.getStringExtra("style");
	    mSourcesound = i.getStringExtra("sourcesound");
	    sharePlaySound = getSharedPreferences("CBplaysound", 1);
	    shareSaveHistory = getSharedPreferences("CBsavehistory", 1);
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        contentview_Content = (WebView) findViewById(R.id.contentview_Content);
    	initWebview();
    	if(wordId > -1)
    	{
    		content = getContentById(wordId);
    	}else
    	{
    		content = getContentByWord(mCurrentWord);
    	}
    	showContent(content);
	}

    public void initWebview()
    {
    	setContentView(R.layout.content);
    	contentview_Content = (WebView) findViewById(R.id.contentview_Content);
    	contentview_Content.getSettings().setSupportZoom(true);         
    	contentview_Content.getSettings().setBuiltInZoomControls(true);
    	contentview_Content.setBackgroundColor(Color.argb(255, 255, 255, 255));
    	contentview_Content.setWebViewClient(new WebViewClient() 
        {
        	public void onPageFinished(WebView view, String url)
        	{
        		if (pd != null)
        		{
        			pd.dismiss();
        			pd = null;
        		}
        	}
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		Log.i(CONTENT_TAG,"WebView link clicked; url = " + url);
        		try
        		{
            		String arrUrlPart[] = url.split("://");
            		
            		if (arrUrlPart[0].equals("entry"))
            		{
            			String content = getContentByWord(arrUrlPart[1]);
            			showContent(content);
            		}
            		else if (arrUrlPart[0].equals("http"))
            		{
            	         try {
            	        	 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));             	        	 
            	         } catch (Exception ex) {
                             // TODO Auto-generated catch block
                             ex.printStackTrace();
            	         }             			
            		}
        		}
        		catch (Exception ex)
        		{
        			ex.printStackTrace();
        		}
        		return true;
        	}
        });
    }
    public String getContentById(int id)
    {
		Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mSelectedDB + "/contentId/" + id);

		@SuppressWarnings("deprecation")
		Cursor result = managedQuery(uri,null,null,null,null);
		
    	String content;
        if (result != null)
        {
        	result.moveToFirst();
        	content = Utility.decodeContent(result.getString(result.getColumnIndex("content")));
        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
        	mCurrentWord = result.getString(result.getColumnIndex("word"));
        	showSound(mCurrentWord);
        	if(shareSaveHistory.getInt("savehistory", 0) == 1)
			{
        		saveHistory(String.valueOf(mCurrentWordId), mCurrentWord);
			}
        }
        else // Word not found
        {
        	content = getString(R.string.errorWordNotFound);
        	mCurrentWordId = -1;
        	mCurrentWord = "";
        	showSound(mCurrentWord);
        }
        content = formatContent(content);
        result.close();        
        return content;
    }
    
    public String getContentByWord(String word)
    {
		Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mSelectedDB + "/contentWord/" + word);

		Log.i(CONTENT_TAG,"uri = " + uri.toString());
		@SuppressWarnings("deprecation")
		Cursor result = managedQuery(uri,null,null,null,null);
		
    	String content;
        if (result != null && result.getCount() > 0)
        {
        	result.moveToFirst();
        	content = Utility.decodeContent(result.getString(result.getColumnIndex("content")));
        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
        	mCurrentWord = result.getString(result.getColumnIndex("word"));
        	showSound(mCurrentWord);
        	if(shareSaveHistory.getInt("savehistory", 0) == 1)
			{
        		saveHistory(String.valueOf(mCurrentWordId), mCurrentWord);
			}
        }
        else
        {
        	content = getString(R.string.errorWordNotFound)+" '"+word+"'";
        	mCurrentWordId = -1;
        	mCurrentWord = "";
        	showSound(mCurrentWord);
        }
        content = formatContent(content);
        result.close();
        return content;
    }
    public String formatContent(String content)
    {
		StringBuilder htmlData = new StringBuilder();
		htmlData.append("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n");
		if (mContentStyle != null && !mContentStyle.equals(""))
		{
			htmlData.append("<head><style type=\"text/css\">"+mContentStyle+"</style></head>\n");
		}
		htmlData.append("<body><font face=\"Times New Roman\" size=\"4\">");
		htmlData.append(content);
		htmlData.append("</font></body></html>");
		return htmlData.toString();
    }
    
    public void showContent(String content)
    {
    	if (content != null)
    	{
    		pd = ProgressDialog.show(this, getString(R.string.working), getString(R.string.loading_content), true,false);    		
    		contentview_Content.loadDataWithBaseURL (null, content, MIMETYPE, ENCODING,"about:blank");
    	}
    }
    public void showSound(String mCurrentWord)
    {
    	Log.i(CONTENT_TAG,"Start sound...");
    	contentview_Sound = (TextView)findViewById(R.id.contentview_Sound);
    	contentview_Sound.setEnabled(false);
    	contentview_Sound.setBackgroundColor(Color.BLACK);
    	if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    		fullPathFilePro = getString(R.string.soundPath) + mSourcesound + "/" + mCurrentWord + ".wav";
        }
        else
        {
        	fullPathFilePro = getString(R.string.soundPathNotSDCard) + mSourcesound + "/" + mCurrentWord + ".wav";
        }
       	//fullPathFilePro = getString(R.string.soundPath) + mSourcesound + "/" + mCurrentWord + ".wav";
		Log.i(CONTENT_TAG,"fullPathFilePro = " + fullPathFilePro);
		f = new File(fullPathFilePro);
		if (f.exists())
		{
			Log.i(CONTENT_TAG,"Audio file found!");
			contentview_Sound.setEnabled(true);
			contentview_Sound.setBackgroundResource(R.drawable.icon_sound);
			contentview_Sound.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(mp.isPlaying() == false)
					{
						mp.start();
					}
					else
					{
						mp.stop();
						mp.start();
					}
					Log.i(CONTENT_TAG,"Pronounciation finished!");
				}
			});
			mp = new MediaPlayer();
			try {
				mp.setDataSource(fullPathFilePro);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				mp.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mp.setLooping(false);
			mp.setVolume(1.0f, 1.0f);
			if(sharePlaySound.getInt("playsound", 0) == 1)
			{
				if(mp.isPlaying() == false)
				{
					mp.start();
				}
				else
				{
					mp.stop();
					mp.start();
				}
			}
		}
		else
		{
			Log.i(CONTENT_TAG,"File doesn't exist!!");
		}
    }
    public void saveHistory(String word_id, String word)
    {
    	ArrayList<InfoHistory> arrayHistory = new ArrayList<InfoHistory>();
    	arrayHistory = mVocabularySQLiteHelper.viewAllHistory();
    	if(arrayHistory.size() < 1)
    	{
	    	mVocabularySQLiteHelper.addHistory(word_id, word);
    	}
    	else
    	{
    		int check = 0;
    		for(int i=0; i< arrayHistory.size(); i++)
	    	{
	    		InfoHistory mInfoHistory = arrayHistory.get(i);
	    		if(word_id.equals(mInfoHistory.getId_word()))
	    		{
	    			check = 1;
	    		}
	    	}
    		if(check == 0)
    		{
    			mVocabularySQLiteHelper.addHistory(word_id, word);
    		}
    	}
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.content, menu);
        return true;
    }
    @SuppressWarnings("deprecation")
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.menu_content_addtolist:
		{
			arrayVocabulary = new ArrayList<InfoVocabulary>();
			arrayVocabulary = mVocabularySQLiteHelper.viewAllVocabulary();
			if(arrayVocabulary.size() < 1)
			{
				Intent mIntent = new Intent(this, Vocabulary.class);
				startActivity(mIntent);
			}
			else
			{
				if(arrayVocabulary.size() == 1)
				{
					InfoVocabulary infoTable = arrayVocabulary.get(0);
					ArrayList<InfoVocabularyContent> mArarayVocabularyContent = mVocabularySQLiteHelper.viewAllVocabularyContent(infoTable.getName_table_vocabulary_content());
					int check = 0;
					for(int i=0; i< mArarayVocabularyContent.size(); i++)
					{
						InfoVocabularyContent mInfoVocabularyContent = mArarayVocabularyContent.get(i);
						if(mCurrentWord.equals(mInfoVocabularyContent.getWord()))
						{
							check = 1;
						}
					}
					if(check == 1)
					{
						Toast.makeText(getBaseContext(), mCurrentWord+" "+getString(R.string.has_existed_in_list), Toast.LENGTH_SHORT).show();
					}
					else
					{
						mVocabularySQLiteHelper.addTableVocabularyContent(infoTable.getName_table_vocabulary_content(), String.valueOf(mCurrentWordId), mCurrentWord,getContentWord(mCurrentWord));
			        	Toast.makeText(getBaseContext(), getString(R.string.add_successful), Toast.LENGTH_SHORT).show();
					}
				}
				else
				{
					LayoutInflater factory = LayoutInflater.from(this);
			    	View view = factory.inflate(R.layout.dictionary_show, null);
			    	ScrollView mScrollView = (ScrollView)view.findViewById(R.id.dictionary_show_dictionary);
			    	final RadioGroup mRadioGroup = new RadioGroup(this);
			    	mRadioGroup.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT));
			    	mRadioGroup.setOrientation(RadioGroup.VERTICAL);
			    	//
			    	for(int i=0; i<arrayVocabulary.size(); i++)
			    	{
			    		RadioButton mRadioButton = new RadioButton(this);
			    		mRadioButton.setId(VIEW_RADIO_ID + i);
			    		infoGetVocabulary = arrayVocabulary.get(i);
			    		mRadioButton.setText(infoGetVocabulary.getName());
			    		mRadioButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
			    		mRadioGroup.addView(mRadioButton, i);
			    		if (arrayVocabulary != null)
			            {
			            	mRadioGroup.check(VIEW_RADIO_ID + i);
			            }
			    	}
			    	mScrollView.addView(mRadioGroup);
			    	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
			    	alertDialogBuilder.setView(view);
			    	alertDialogBuilder.setTitle(R.string.select_list_vocabulary);
			    	alertDialogBuilder.setIcon(R.drawable.icon);
			    	alertDialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
			            @Override
			            public void onCancel(DialogInterface dialog) {
			                finish();
			            }
			        }).setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
			            @SuppressWarnings("unused")
						@Override
			            public void onClick(DialogInterface dialog, int which) {
			        		int selectedIndex = mRadioGroup.getCheckedRadioButtonId();
			        		if (selectedIndex < 0)
			        		{
			        			selectedIndex = 0;
			        		}
			        		infoGetVocabulary = arrayVocabulary.get(selectedIndex - VIEW_RADIO_ID);
			        		String nameTableVocabulary = infoGetVocabulary.getName_table_vocabulary_content();
							InfoVocabulary infoTable = arrayVocabulary.get(selectedIndex - VIEW_RADIO_ID);
							ArrayList<InfoVocabularyContent> mArarayVocabularyContent = mVocabularySQLiteHelper.viewAllVocabularyContent(infoTable.getName_table_vocabulary_content());
							int check = 0;
							for(int i=0; i< mArarayVocabularyContent.size(); i++)
							{
								InfoVocabularyContent mInfoVocabularyContent = mArarayVocabularyContent.get(i);
								if(mCurrentWord.equals(mInfoVocabularyContent.getWord()))
								{
									check = 1;
								}
							}
							if(check == 1)
							{
								Toast.makeText(getBaseContext(), mCurrentWord+" "+getString(R.string.has_existed_in_list), Toast.LENGTH_SHORT).show();
							}
							else
							{
								mVocabularySQLiteHelper.addTableVocabularyContent(infoTable.getName_table_vocabulary_content(), String.valueOf(mCurrentWordId), mCurrentWord,getContentWord(mCurrentWord));
					        	Toast.makeText(getBaseContext(), getString(R.string.add_successful), Toast.LENGTH_SHORT).show();
							}
						
			            }
			        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					});
			    	Dialog dialog = alertDialogBuilder.create();
			        dialog.show();
				}
			}
		}break;
		case R.id.menu_content_exit:
		{
			finish();
		}break;
    	}
    	return super.onOptionsItemSelected(item);
    }
    private String getContentWord(String word)
    {
    	String mDBExtension;
    	String mDBPath;
        mDBExtension = getResources().getString(R.string.dbExtension);
        mDBPath = getResources().getString(R.string.dbPath);
        DatabaseFileList mDBList = new DatabaseFileList(mDBPath,mDBExtension);
    	DatabaseFile mDBFile;
    	mDBFile = mDBList.items.get(0);
    	Cursor result;
		Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mDBFile.fileName + "/contentWord/" + word);
		result = getContentResolver().query(uri,null,null,null,null);
		String mCurrentContent = null;
        if (result != null && result.getCount() > 0)
        {
        	result.moveToFirst();
        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
        	mCurrentWord = result.getString(result.getColumnIndex("word"));
        	mCurrentContent = result.getString(result.getColumnIndex("content"));
        }
		return mCurrentContent;
    }
    
}
